package com.tieba.interceptor;


import com.alibaba.fastjson.JSONObject;
import com.tieba.pojo.Result;
import com.tieba.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@RestController
public class LoginCheckInterceptor implements HandlerInterceptor {

    //在目标资源方法运行前运行，返回true放行，false，不放行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

//        response.setHeader("Access-Control-Allow-Origin", "*");
//        response.setHeader("Access-Control-Allow-Credentials", "true");
//        response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS");
//        response.setHeader("Access-Control-Max-Age", "86400");
//        response.setHeader("Access-Control-Allow-Headers", "*");

        // 如果是OPTIONS则结束请求
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            log.info("Options请求");
            response.setStatus(HttpStatus.NO_CONTENT.value());
            return true;
        }


//        Enumeration<String> headerNames = request.getHeaderNames();
//        while (headerNames.hasMoreElements()) {
//            String headerName = headerNames.nextElement();
//            log.info("Header: {} = {}", headerName, request.getHeader(headerName));
//        }
        //获取url
        String url = request.getRequestURI();
        log.info("请求的url:{}", url);

        //判断url中是否包含login,如果包含则说明是登录操作，放行
        //在登录请求中会发放jwt令牌
        //在配置类排除了登录路径
        if (url.contains("login")) {
            log.info("登录操作，放行");
            return true;
        }

        //如果不是登录操作，尝试获取请求头的令牌
        String jwt = request.getHeader("Token");
        log.info("请求的token:{}", jwt);
        if (StringUtils.isEmpty(jwt)) {
            log.info("token为空");
        }

        //判断令牌是否存在，如果不存在返回错误信息
        if (!StringUtils.hasLength(jwt)) {
            log.info("请求头token为空，返回未登录的信息");
            Result error = Result.error("NOT_LOGIN");//统一响应格式
            //手动转换对象为json格式------------>阿里巴巴fastjson
            String notlogin = JSONObject.toJSONString(error);
            response.getWriter().write(notlogin);//响应
            return false;
        }

        //校验token,如果失败则返回错误结果
        try {
            Claims c = JwtUtils.parseJWT(jwt);
            Integer userId = (Integer)c.get("id");
            log.info("解析得到的userId为:{}", userId);
            request.setAttribute("userId", userId);

            //log.info("JWTuserId:{}", userId);
        } catch (Exception e) {
            log.info("解析失败，返回未登录的错误信息");
            Result error = Result.error("NOT_LOGIN");
            //手动转换对象为json格式------------>阿里巴巴fastjson
            String notlogin = JSONObject.toJSONString(error);
            response.getWriter().write(notlogin);

            return false;
        }

        //没有任何问题，直接放行
        log.info("令牌合法，放行");
        return true;
    }

    //目标资源方法运行之后运行
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle ...");
    }

    //视图渲染完毕后运行，最后运行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion ...");
    }
}
